package com.snowflake.ecatalog.web.profile;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.Servlets;

import com.snowflake.ecatalog.entity.Goods;
import com.snowflake.ecatalog.entity.ResourceInfo;
import com.snowflake.ecatalog.service.profile.GoodsCategoryService;
import com.snowflake.ecatalog.service.profile.GoodsService;
import com.snowflake.ecatalog.util.FileOperateUtil;
import com.snowflake.ecatalog.util.LoginUtil;

/**
 * 商品管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /goods/ Create page : GET /goods/create Create action : POST
 * /goods/create Update page : GET /goods/update/{id} Update action : POST
 * /goods/update Delete action : GET /goods/delete/{id}
 * 
 */
@Controller
@RequestMapping(value = "/goods")
public class GoodsController {

	private static final int PAGE_SIZE = 10;

	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsCategoryService goodsCategoryService;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model,
			ServletRequest request, HttpSession session) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Long profileId = LoginUtil.getProfileIdFromSession(session);
		Page<Goods> goods = goodsService.getGoods(profileId, searchParams, pageNumber, PAGE_SIZE);
		model.addAttribute("goods", goods);
		// if (searchParams.size() == 0) {
		// searchParams.put("EQ_status", "");
		// }
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "profile/goodsList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model, ServletRequest request) {
		Long profileId = LoginUtil.getProfileIdFromRequest(request);
		model.addAttribute("goods", new Goods());
		model.addAttribute("action", "create");
		model.addAttribute("goodsCategorys", goodsCategoryService.getEnabledGoodsCategory(profileId));
		return "profile/goodsForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Goods newGoods, RedirectAttributes redirectAttributes, ServletRequest request)
			throws Exception {
		List<ResourceInfo> resourceInfoList = FileOperateUtil.upload((HttpServletRequest) request,
				String.valueOf(LoginUtil.getProfileIdFromRequest(request)));
		goodsService.saveGoods(newGoods, resourceInfoList);
		redirectAttributes.addFlashAttribute("message", "创建 商品成功");
		return "redirect:/goods/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model, ServletRequest request) {
		Long profileId = LoginUtil.getProfileIdFromRequest(request);
		Goods goods = goodsService.getGoods(id);
		model.addAttribute("goods", goods);
		Map<Integer, ResourceInfo> map = goodsService.getImgPathMap(goods.getId());
		model.addAttribute("uploadFileName",
				FileOperateUtil.getFileNameByResourceInfos(Collections3.getFirst(map.values())));
		model.addAttribute("action", "update");
		model.addAttribute("goodsCategorys", goodsCategoryService.getEnabledGoodsCategory(profileId));
		return "profile/goodsForm";
	}

	@RequestMapping(value = "getImgPath", method = RequestMethod.POST)
	public @ResponseBody
	Map<Integer, ResourceInfo> getImgPath(@RequestParam("id") Long id) {
		return goodsService.getImgPathMap(id);
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadGoods") Goods goods, RedirectAttributes redirectAttributes,
			ServletRequest request) throws Exception {
		List<ResourceInfo> resourceInfoList = FileOperateUtil.upload((HttpServletRequest) request,
				String.valueOf(LoginUtil.getProfileIdFromRequest(request)));
		goodsService.updateGoods(goods, resourceInfoList);
		redirectAttributes.addFlashAttribute("message", "更新商品成功");
		return "redirect:/goods/";
	}

	@RequestMapping(value = "enable/{id}")
	public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		if (goodsService.checkEnableGoods(id)) {
			goodsService.enableGoods(id);
			redirectAttributes.addFlashAttribute("message", "启用商品成功");
		} else {
			redirectAttributes.addFlashAttribute("message", "商品未上传完整，启用商品失败");
		}
		return "redirect:/goods/";
	}

	@RequestMapping(value = "disable/{id}")
	public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		goodsService.disableGoods(id);
		redirectAttributes.addFlashAttribute("message", "禁用商品成功");
		return "redirect:/goods/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		goodsService.deleteGoods(id);
		redirectAttributes.addFlashAttribute("message", "删除商品成功");
		return "redirect:/goods/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Goods对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadGoods")
	public Goods getGoods(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			Goods goods = goodsService.getGoods(id);
			goods.setCategory(null);
			return goods;
		}
		return null;
	}
}
